<!--
 * @Author: 梁青春
 * @Date: 2025-11-04 15:22:00
 * @LastEditors: 梁青春
 * @Description: 新增下达规则 - 表单页面（严格参照原型图二）
-->
<template>
  <div class="main-container issue-add-form">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">新增下达规则</h2>
      </div>
      <div class="header-right">
        <el-button icon="ArrowLeft" @click="handleBack" class="default-btn op-btn"> 返回 </el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading" class="add-btn op-btn">
          保存
        </el-button>
      </div>
    </div>

    <!-- 规则表单卡片 -->
    <div class="form-container">
      <el-card class="form-card">
        <template #header>
          <span class="card-title">规则内容</span>
        </template>

        <!-- 表单主体 -->
        <el-form ref="ruleFormRef" :model="ruleForm" label-width="160px" class="rule-form">
          <!-- 如果医嘱：患者病区包含 -->
          <el-form-item>
            <template #label>
              <div class="inline-label">
                <el-checkbox v-model="ruleForm.enableWard">患者病区包含</el-checkbox>
              </div>
            </template>
            <!-- 当启用时才可编辑，且必须选择 -->
            <el-select
              v-model="ruleForm.wards"
              placeholder="请选择病区"
              :disabled="!ruleForm.enableWard"
              multiple
              style="width: 360px"
              clearable
            >
              <el-option v-for="w in wardOptions" :key="w.value" :label="w.label" :value="w.value" />
            </el-select>
          </el-form-item>

          <!-- 如果医嘱：来源科室包含 -->
          <el-form-item>
            <template #label>
              <div class="inline-label">
                <el-checkbox v-model="ruleForm.enableSourceDept">来源科室包含</el-checkbox>
              </div>
            </template>
            <el-select
              v-model="ruleForm.sourceDepts"
              placeholder="请选择科室"
              :disabled="!ruleForm.enableSourceDept"
              multiple
              style="width: 360px"
              clearable
            >
              <el-option v-for="d in deptOptions" :key="d.value" :label="d.label" :value="d.value" />
            </el-select>
          </el-form-item>

          <!-- 如果医嘱：药品类型包含 -->
          <el-form-item>
            <template #label>
              <div class="inline-label">
                <el-checkbox v-model="ruleForm.enableDrugType">药品类型包含</el-checkbox>
              </div>
            </template>
            <el-select
              v-model="ruleForm.drugType"
              placeholder="请选择药品类型"
              :disabled="!ruleForm.enableDrugType"
              style="width: 360px"
              clearable
            >
              <el-option v-for="t in drugTypeOptions" :key="t.value" :label="t.label" :value="t.value" />
            </el-select>
            <!-- 右侧说明文字：当选择中药时，下方中药加工可选 -->
            <span class="helper-text">如果药品类型选择中药，下面中药加工包含可选</span>
          </el-form-item>

          <!-- 如果医嘱：中药加工包含（当药品类型为中药时启用） -->
          <el-form-item>
            <template #label>
              <div class="inline-label">
                <el-checkbox v-model="ruleForm.enableTcmProcess" :disabled="ruleForm.drugType !== '中药'">
                  中药加工包含
                </el-checkbox>
              </div>
            </template>
            <el-select
              v-model="ruleForm.tcmProcess"
              placeholder="请选择中药加工方式"
              :disabled="!(ruleForm.enableTcmProcess && ruleForm.drugType === '中药')"
              style="width: 360px"
              clearable
            >
              <el-option v-for="p in tcmProcessOptions" :key="p.value" :label="p.label" :value="p.value" />
            </el-select>
          </el-form-item>

          <!-- 则：医嘱下达至 -->
          <el-form-item label="则：医嘱下达至">
            <el-select v-model="ruleForm.deliverTo" placeholder="请选择" style="width: 360px" clearable>
              <el-option label="本地药房" value="本地药房" />
              <el-option label="中心药房" value="中心药房" />
            </el-select>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup name="OrderIssueAddForm">
import { ref, reactive, watch, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { mockOrderIssueApi } from '@/mock/orderIssue'

const proxy = getCurrentInstance().proxy
const router = useRouter()

// 提交状态
const submitLoading = ref(false)
const ruleFormRef = ref(null)

// 下拉选项数据（真实环境应从接口加载，这里使用 mock 数据）
const wardOptions = ref([
  { label: '全部病区', value: '全部病区' },
  { label: '一病区', value: '一病区' },
  { label: '二病区', value: '二病区' }
])
const deptOptions = ref([
  { label: '全部科室', value: '全部科室' },
  { label: '心内科', value: '心内科' },
  { label: '外科', value: '外科' }
])
const drugTypeOptions = ref([
  { label: '医疗器械', value: '医疗器械' },
  { label: '西药', value: '西药' },
  { label: '中成药', value: '中成药' },
  { label: '中药', value: '中药' },
  { label: '中药饮片', value: '中药饮片' },
  { label: '中药颗粒', value: '中药颗粒' }
])
const tcmProcessOptions = ref([
  { label: '先煎', value: '先煎' },
  { label: '后下', value: '后下' },
  { label: '包煎', value: '包煎' }
])

// 表单数据与开关
const ruleForm = reactive({
  enableWard: true,
  wards: ['全部病区'],
  enableSourceDept: true,
  sourceDepts: ['全部科室'],
  enableDrugType: true,
  drugType: '医疗器械',
  enableTcmProcess: false, // 默认不启用，仅当药品类型为“中药”时可开启
  tcmProcess: '',
  deliverTo: '本地药房'
})

// 当药品类型为“中药”时，允许勾选“中药加工包含”
watch(
  () => ruleForm.drugType,
  val => {
    if (val !== '中药') {
      ruleForm.enableTcmProcess = false
      ruleForm.tcmProcess = ''
    }
  }
)

// 返回列表页（Tab 主页面）
const handleBack = () => {
  router.replace('/baseinfo/orderIssueSettings')
}

// 表单校验（根据开关动态校验）
const validateRuleForm = () => {
  // 当启用病区条件时，必须选择病区
  if (ruleForm.enableWard && (!ruleForm.wards || ruleForm.wards.length === 0)) {
    proxy.$modal.notifyWarning('请选择病区')
    return false
  }
  // 当启用来源科室条件时，必须选择科室
  if (ruleForm.enableSourceDept && (!ruleForm.sourceDepts || ruleForm.sourceDepts.length === 0)) {
    proxy.$modal.notifyWarning('请选择来源科室')
    return false
  }
  // 当启用药品类型条件时，必须选择药品类型
  if (ruleForm.enableDrugType && !ruleForm.drugType) {
    proxy.$modal.notifyWarning('请选择药品类型')
    return false
  }
  // 当启用中药加工时，必须选择加工方式
  if (ruleForm.enableTcmProcess && ruleForm.drugType === '中药' && !ruleForm.tcmProcess) {
    proxy.$modal.notifyWarning('请选择中药加工方式')
    return false
  }
  // 下达至必须选择
  if (!ruleForm.deliverTo) {
    proxy.$modal.notifyWarning('请选择医嘱下达至')
    return false
  }
  return true
}

// 提交保存
const handleSubmit = async () => {
  try {
    if (!validateRuleForm()) return
    submitLoading.value = true
    // 组装提交数据
    const payload = {
      wards: ruleForm.enableWard ? ruleForm.wards : [],
      sourceDepts: ruleForm.enableSourceDept ? ruleForm.sourceDepts : [],
      drugType: ruleForm.enableDrugType ? ruleForm.drugType : '',
      tcmProcess: ruleForm.enableTcmProcess && ruleForm.drugType === '中药' ? ruleForm.tcmProcess : '',
      deliverTo: ruleForm.deliverTo
    }
    const res = mockOrderIssueApi.addIssueRule(payload)
    if (res.code === 200) {
      proxy.$modal.notifySuccess(res.message || '新增成功')
      router.push('/baseinfo/orderIssueSettings')
    } else {
      proxy.$modal.notifyWarning(res.message || '新增失败')
    }
  } catch (error) {
    console.error('新增规则失败:', error)
    proxy.$modal.notifyWarning('新增规则失败')
  } finally {
    submitLoading.value = false
  }
}

onMounted(() => {})
</script>

<style lang="scss" scoped>
.issue-add-form {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    .page-title {
      font-size: 18px;
      font-weight: 600;
    }
    .op-btn {
      margin-left: 8px;
    }
  }

  .card-title {
    font-weight: 600;
  }

  .inline-label {
    display: flex;
    align-items: center;
  }

  .helper-text {
    color: #f56c6c;
    font-size: 12px;
    margin-left: 12px;
  }
}
</style>
